package com.alipay.sofa.award.record.biz.impl;

import com.alipay.common.event.UniformEvent;
import com.alipay.common.event.UniformEventContext;
import com.alipay.common.event.UniformEventMessageListener;
import com.alipay.sofa.award.record.common.dal.dao.AwardRecordMapper;
import com.alipay.sofa.award.record.common.dal.dataobject.AwardRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * MqRecordMessageListener
 *
 * @author yangguanchao
 * @since 2018/09/03
 */
public class MqRecordMessageListener implements UniformEventMessageListener {

    private static final Logger logger = LoggerFactory.getLogger(MqRecordMessageListener.class);

    @Autowired
    private AwardRecordMapper   awardRecordMapper;

    @Override
    public void onUniformEvent(UniformEvent message, UniformEventContext context) throws Exception {
        /* get TOPIC, EVENTCODE and payload from the message instance */
        final String topic = message.getTopic();
        final String eventcode = message.getEventCode();
        final String id = message.getId();
        final Object businessObject = message.getEventPayload();

        logger.info("Receive a message, TOPIC [{}] EVENTCODE [{}] id [{}] payload [{}]",
            new Object[] { topic, eventcode, id, businessObject });

        try {
            boolean processSuccess = processMessage(businessObject);

            if (!processSuccess) {
                /* Process the message failure, set cause and rollback, the message is re-delivered later. */
                context.setContextDesc("process error cause");
                context.setRollbackOnly();
            }
        } catch (Exception e) {
            logger.error("Process a message, failure. TOPIC [{}] EVENTCODE [{}] id [{}] error {}",
                new Object[] { topic, eventcode, id, e.getMessage() }, e);
            /* When any exception is thrown, the message is re-delivered later. */
            throw e;
        }
    }

    /* Process the business logic */
    private boolean processMessage(Object businessObject) {
        if (!(businessObject instanceof AwardRecord)) {
            logger.error("Current msg received [" + businessObject.getClass()
                         + "] is not instance of " + AwardRecord.class);
            return true;
        }
        AwardRecord awardRecord = (AwardRecord) businessObject;
        this.awardRecordMapper.insert(awardRecord);
        return true;
    }
}
